import React, { useState, useEffect, useCallback, useMemo } from 'react'
import './systeminfo.scss'
import bytes from 'bytes'
import moment from 'moment'
import { Row, Col, Card, Progress, Empty } from 'antd'
import { totalPercentage } from '../../../../utils'
import { serviceGetInnerMessage } from '../../../../request/innermessage'
import { sys } from 'typescript'
import { serviceGetSystemInfo } from '../../../../request/system'
import CONFIG from '../../../../config'

interface Props {
  systemInfo: {
    [key: string]: any
  }
}
interface State {
  curSystemTime: string
  messageList: any[]
  loading: boolean
}

const initialState: State = {
  curSystemTime: '',
  messageList: [],
  loading: true,
}

const statusColor = (percentage: number) => {
  if (percentage < 40) return '#52c41a'
  if (percentage < 80) return '#ffa500'
  return '#f50'
}

const System: React.FC<Props> = function ({ systemInfo }: Props) {
  const [curSystemTime, setCurSystemTime] = useState('')
  const [messageList, setMessageList] = useState([])
  const [loading, setLoading] = useState(true)

  // 返回一个memorized的CPU使用率百分比
  const memPercentage = useMemo(() => {
    return totalPercentage(systemInfo.totalmem, systemInfo.freemem)
  }, [systemInfo.totalmem, systemInfo.freemem])

  // 倒计时
  // useCallback返回一个memoized回调函数。传入 `useCallback` 的函数会在渲染期间执行。请不要在这个函数内部执行与渲染无关的操作，诸如副作用这类的操作属于 `useEffect` 的适用范畴，而不是 `useCallback`。
  const countdown = useCallback(() => {
    // 接收发送过来的时间和当前实际时间是有一定的间隔，弥补这个间隔
    const timeDiff =
      systemInfo.currentSystemTime + (Date.now() - systemInfo.currentSystemTime)
    setCurSystemTime(moment(timeDiff).format('YYYY-MM-DD HH:mm:ss'))
  }, [systemInfo.currentSystemTime])

  let timer: NodeJS.Timeout
  useEffect(() => {
    countdown()
    timer = setTimeout(() => {
      countdown()
    }, 1000)
    return () => {
      if (timer) clearTimeout(timer)
    }
  }, [countdown])

  useEffect(() => {
    serviceGetInnerMessage({ pagesize: 5 }).then(res => {
      if (res.data.success) {
        setLoading(false)
        setMessageList(res.data.data.rows)
      }
    })
  }, [])

  return (
    <Row
      className="system-data"
      gutter={{ xs: 8, sm: 16, md: 24, lg: 32, xl: 40 }}
    >
      <Col xl={8} lg={12} md={12} sm={24} xs={24}>
        <Card title="系统参数" hoverable loading={!systemInfo.nodeVersion}>
          <p className="item-text ellipsis">
            <em>Node版本：</em>
            {systemInfo.nodeVersion}
          </p>
          <p className="item-text ellipsis">
            <em>MySQL版本：</em>
            {systemInfo.mysqlVersion}
          </p>
          <p className="item-text ellipsis">
            <em>当前环境：</em>
            {CONFIG.isProduction ? '生产环境' : '开发环境'}
          </p>
          <p className="item-text ellipsis">
            <em>系统时间：</em>
            {curSystemTime}
          </p>
        </Card>
      </Col>
      <Col xl={8} lg={12} md={12} sm={24} xs={24}>
        <Card title="我的消息" hoverable loading={loading}>
          {messageList.length > 0 ? (
            messageList.map((item: any) => (
              <p className="item-text" key={item.id}>
                <em>{item.content}</em>
              </p>
            ))
          ) : (
            <Empty />
          )}
        </Card>
      </Col>
      <Col xl={8} lg={12} md={12} sm={24} xs={24}>
        <Card
          className="mem"
          title={`内存使用率(${bytes(systemInfo.totalmem)})`}
          hoverable
        >
          <Progress
            type="circle"
            percent={memPercentage}
            strokeColor={statusColor(memPercentage)}
            format={percent => percent + '%'}
          />
          <div className="surplus">剩余{bytes(systemInfo.freemem)}</div>
        </Card>
      </Col>
    </Row>
  )
}

export default System
